package com.common.vo;

import com.common.listener.MyServletContextListener;
import com.common.thread.MqttMsgThread;
import com.common.thread.MqttSendMsgThread;
import com.common.util.WindowsUtil;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.Random;

/**
 * 消息推送
 *
 * @author 57300
 */
public class MqttMessage {

    private MqttClient client;
    private String host = "tcp://baidu.cn:61613";// 服务器地址
    private String userName = "admin";
    private String passWord = "admin";
    private String myTopic = "gstar/client";// 总类/设备是/device   客户端是client  结尾序列号是设备的mac地址+CPU的后四位
    private static MqttMessage gstarPush;

    public static MqttMessage getInstance() {
        if (gstarPush == null) {
            synchronized (MqttMessage.class){
                if (gstarPush == null) {
                    gstarPush = new MqttMessage();
                }
            }
        }
        return gstarPush;
    }

    private MqttMessage() {
        try {
            Random random = new Random();
            int nextInt = random.nextInt(1000);
            client = new MqttClient(host, "admin" + nextInt, new MemoryPersistence());
            connect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public MqttClient getClient(){
        return this.client;
    }

    public String getMyTopic(){
        return this.myTopic;
    }


    /**
     * 初始化连接
     */
    public void connect() {
        final MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(true);
        options.setUserName(userName);
        options.setPassword(passWord.toCharArray());
        // 设置超时时间
        options.setConnectionTimeout(10);
        // 设置会话心跳时间
        options.setKeepAliveInterval(20);
        try {
            client.setCallback(new MqttCallback() {

                @Override
                public void connectionLost(Throwable cause) {
                    try {
//						client.connect(options);
//						client.subscribe(myTopic+"/"+client.getClientId());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                }

                /**
                 * 本机作为【客户端】接收的数据
                 */
                @Override
                public void messageArrived(String topic, org.eclipse.paho.client.mqttv3.MqttMessage arg1) throws Exception {
                    try {
                        // 接收数据处理
                        String string = new String(arg1.getPayload(), "UTF-8");
                        JSONObject obj = new JSONObject(string);
                        //String title = (String) obj.get("title");
                        String clientId = (String) obj.get("clientId");
                        JSONObject content = (JSONObject) obj.get("content");
                        new Thread(new MqttMsgThread(content)).start();
                        // 接收完后回传告知
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("data", WindowsUtil.getCPUSerialNumber());
                        jsonObject.put("msg", "推送成功");
                        new Thread(new MqttSendMsgThread(MyServletContextListener.mqttMessage, clientId, jsonObject.toString())).start();
                        //sendMessage(clientId, jsonObject.toString());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            client.connect(options);
            client.subscribe(myTopic + "/" + WindowsUtil.getCPUSerialNumber()); // 使用本地序列号订阅
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取客户端ID
     * @return
     */
    public String getClientId() {
        return client.getClientId();
    }

    /**
     * 发送消息【客户端/服务端】
     * @param clientId
     * @param message
     * @return
     */
    public String sendMessage(String clientId, String message) {
        try {
            if (client == null || !client.isConnected()) {
                connect();
            }
            if (clientId == null) {
                clientId = "";
            }
            if (message != null && !message.equals("")) {
                // 发布自己的消息
                client.publish(myTopic + "/" + clientId, message.getBytes("UTF-8"), 0, false);
            } else {
                return "消息内容不能未空";
            }
        } catch (MqttException e) {
            e.printStackTrace();
            return "消息推送异常";
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            /*if (client != null) {
                try {
                    client.disconnect();
                } catch (MqttException e1) {
                    e1.printStackTrace();
                }
            }
            client = null;*/
        }
        return "消息推送成功";
    }

    /**
     * 关闭连接
     */
    public void disConnect() {
        try {
            client.disconnect();
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }




}
